<!--接口维护 add by gaojingyu-->
<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters" @submit.native.prevent>
        <el-form-item>
          <el-input
            clearable
            v-model="filters.interface_name_zh"
            prefix-icon="el-icon-search"
            placeholder="接口名称"
            @keyup.enter.native="getLyzdInterfaceList"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getLyzdInterfaceList"
            >查询</el-button
          >
        </el-form-item>

        <el-form-item>
          <router-link
            :to="{ path: 'addInterface' }"
            style="text-decoration: none;color: aliceblue;"
          >
            <el-button type="primary">新增</el-button>
          </router-link>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="download"
            >下载模板<i class="el-icon-download el-icon--right"></i
          ></el-button>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="upload"
            >接口上传<i class="el-icon-upload el-icon--right"></i
          ></el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <el-dialog
      title="接口上传"
      :visible.sync="uploadform"
      :close-on-click-modal="false"
      style="width: 95%; left: 2.5%"
    >
      <el-form
        :model="editForm"
        label-width="80px"
        :rules="editFormRules"
        ref="editForm"
      >
        <el-form-item>
          <el-upload
            ref="uploadExcel"
            :action="uploadurl"
            :limit="limitNum"
            :auto-upload="false"
            accept=".xlsx"
            :before-upload="beforeUploadFile"
            :on-change="fileChange"
            :on-exceed="exceedFile"
            :on-success="handleSuccess"
            :on-error="handleError"
            :file-list="fileList"
          >
            <el-button size="small" plain>选择文件</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传xlsx(Excel2007)文件，且不超过10M
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="uploadFile"
          >立即上传</el-button
        >
        <el-button size="small" @click.native="uploadform = false"
          >取消</el-button
        >
      </div>
    </el-dialog>

    <!--列表-->
    <el-table
      :data="project"
      highlight-current-row
      v-loading="listLoading"
      @selection-change="selsChange"
      style="width: 100%;"
    >
      <el-table-column type="selection" min-width="5%"> </el-table-column>
      <el-table-column
        type="index"
        align="center"
        :index="indexMethod"
        label="序号"
      />
      <el-table-column
        prop="interface_name_zh"
        label="接口中文名称"
        min-width="12%"
      >
      </el-table-column>
      <el-table-column
        prop="interface_name_en"
        label="方法名称"
        min-width="12%"
      >
      </el-table-column>
      <el-table-column prop="delete_flag" label="状态" min-width="5%">
        <template slot-scope="scope">
          <img
            v-show="!scope.row.delete_flag"
            src="../../../../assets/icon-yes.svg"
          />
          <img
            v-show="scope.row.delete_flag"
            src="../../../../assets/icon-no.svg"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="25%">
        <template slot-scope="scope">
          <el-button
            plain
            size="small"
            type="warning"
            @click="handleResult(scope.$index, scope.row)"
            >编辑
          </el-button>

          <el-button
            plain
            type="success"
            size="small"
            @click="handleInfo(scope.$index, scope.row)"
            >详情</el-button
          >
          <el-button
            type="info"
            size="small"
            @click="handleChangeStatus(scope.$index, scope.row)"
            >{{ scope.row.delete_flag === true ? "启用" : "禁用" }}</el-button
          >
          <el-button
            plain
            type="success"
            size="small"
            @click="handleInfoCopy(scope.$index, scope.row)"
            >复制</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <!--  <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>-->
      <span
        >当前页<a>{{ currentCount }}</a
        >条/共<a>{{ totalCount }}</a
        >条</span
      >
      <el-pagination
        layout="prev, pager, next"
        @current-change="handleCurrentChange"
        :page-size="20"
        :page-count="total"
        style="float:right;"
      >
      </el-pagination>
    </el-col>
  </section>
</template>

<script>
import { test, getLyzdInterface, editStatus_api } from "../../../../api/api";
export default {
  data() {
    return {
      filters: {
        name: "",
      },
      limitNum: 1,
      formLabelWidth: "80px",
      form: {
        file: "",
      },
      fileList: [],

      project: [],
      total: 0,
      totalCount: 0,
      currentCount: 0,
      page: 1,
      listLoading: false,
      sels: [], //列表选中列
      editFormVisible: false, //编辑界面是否显示
      editLoading: false,
      uploadform: false,
      uploadurl: test + "/api/api/InterfaceExcleImport",
      editFormRules: {
        env_name: [
          { required: true, message: "请输入环境名称", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "长度在 1 到 50 个字符",
            trigger: "blur",
          },
        ],
        address: [
          { required: true, message: "请输入地址", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "长度在 1 到 50 个字符",
            trigger: "blur",
          },
        ],
        content: [
          { required: true, message: "请输入描述", trigger: "blur" },
          { max: 255, message: "不能超过125个字符", trigger: "blur" },
        ],
      },
      //编辑界面数据
      editForm: {
        name: "",
        version: "",
        type: "",
        description: "",
      },
      addFormVisible: false, //新增界面是否显示
      addLoading: false,
      addFormRules: {
        env_name: [
          { required: true, message: "请输入环境名称", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "长度在 1 到 50 个字符",
            trigger: "blur",
          },
        ],

        address: [
          { required: true, message: "请输入地址", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "长度在 1 到 50 个字符",
            trigger: "blur",
          },
        ],
        content: [
          { required: true, message: "请输入描述", trigger: "blur" },
          { max: 255, message: "不能超过125个字符", trigger: "blur" },
        ],
      },
      //新增界面数据
      addForm: {
        name: "",
        version: "",
        type: "",
        description: "",
      },
    };
  },
  methods: {
    // 获取项目列表 getLyzdEnvironments getLyzdEnvironments getLyzdInterfaceList
    getLyzdInterfaceList() {
      this.listLoading = true;
      let self = this;
      let params = {
        page: self.page,
        interface_name_zh: self.filters.interface_name_zh,
      };

      let headers = {
        Authorization: "Token " + JSON.parse(sessionStorage.getItem("token")),
      };
      getLyzdInterface(headers, params).then((res) => {
        self.listLoading = false;
        let { msg, code, data } = res;
        if (code === "999999") {
          self.total = data.total;
          self.project = data.data;

          this.totalCount = data.totalCount;
          this.currentCount = data.data.length;
        } else {
          self.$message.error({
            message: msg,
            center: true,
          });
        }
      });
    },

    exceedFile(files, fileList) {
      this.$notify.warning({
        title: "警告",
        message: `只能选择 ${
          this.limitNum
        } 个文件，当前共选择了 ${files.length + fileList.length} 个`,
      });
    },
    // 文件状态改变时的钩子
    fileChange(file, fileList) {
      this.form.file = file.raw;
    },
    // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
    beforeUploadFile(file) {
      let extension = file.name.substring(file.name.lastIndexOf(".") + 1);
      let size = file.size / 1024 / 1024;
      if (extension !== "xlsx") {
        this.$notify.warning({
          title: "警告",
          message: `只能上传Excel2017（即后缀是.xlsx）的文件`,
        });
      }
      if (size > 10) {
        this.$notify.warning({
          title: "警告",
          message: `文件大小不得超过10M`,
        });
      }
    },

    upload() {
      this.uploadform = true;
    },
    //接口导入模板下载
    download() {
      $.ajax({
        type: "get",
        url: test + "/api/api/InterfaceTemplateDownload",
        async: true,
        //data: param,
        headers: {
          Authorization: "Token " + JSON.parse(sessionStorage.getItem("token")),
        },
        timeout: 5000,
        success: function(data) {
          if (data.code === "999999") {
            window.open(test + "/api/api/download_doc?url=" + data.path);
          } else {
            self.$message.error({
              message: data.msg,
              center: true,
            });
          }
        },
      });
    },
    indexMethod(index) {
      let curpage = this.page; //单前页码，具体看组件取值

      let limitpage = 20; //每页条数，具体是组件取值

      return index + 1 + (curpage - 1) * limitpage;
    },

    // 文件上传成功时的钩子
    handleSuccess(res, file, fileList) {
      if (res.code == "999999") {
        this.$notify.success({
          title: "成功",
          message: `文件上传成功`,
        });
        this.$refs.uploadExcel.clearFiles();
      } else {
        this.$confirm(res.data, res.msg, { type: "info" });
        this.$refs.uploadExcel.clearFiles();
      }
    },
    // 文件上传失败时的钩子
    handleError(err, file, fileList) {
      this.$notify.error({
        title: "错误",
        message: `文件上传失败`,
      });
      this.$refs.uploadExcel.clearFiles();
    },
    uploadFile() {
      this.$refs.uploadExcel.submit();
    },
    //删除
    handleDel: function(index, row) {
      this.$confirm("确认删除该记录吗?", "提示", {
        type: "warning",
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        let self = this;
        let params = { ids: [row.id] };
        let header = {
          "Content-Type": "application/json",
          Authorization: "Token " + JSON.parse(sessionStorage.getItem("token")),
        };
        delEnvironment(header, params).then((_data) => {
          let { msg, code, data } = _data;
          if (code === "999999") {
            self.$message({
              message: "删除成功",
              center: true,
              type: "success",
            });
          } else {
            self.$message.error({
              message: msg,
              center: true,
            });
          }
          self.getLyzdInterfaceList();
        });
      });
    },
    // 改变项目状态
    handleChangeStatus: function(index, row) {
      let self = this;
      this.listLoading = true;
      let params = { api_id: row.id };

      let headers = {
        Authorization: "Token " + JSON.parse(sessionStorage.getItem("token")),
      };
      editStatus_api(headers, params).then((_data) => {
        let { msg, code, data } = _data;
        self.listLoading = false;
        if (code === "999999") {
          self.$message({
            message: msg,
            center: true,
            type: "success",
          });

          row.delete_flag = !row.delete_flag;
        } else {
          self.$message.error({
            message: msg,
            center: true,
          });
        }
      });
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getLyzdInterfaceList();
    },
    //显示编辑界面
    handleEdit: function(index, row) {
      this.editFormVisible = true;
      this.editForm = Object.assign({}, row);
    },
    //跳转用
    handleResult: function(index, row) {
      let api_id = row.id;
      this.$router.push({ path: "/interface_edit/cid=" + api_id });
    },

    beforeRouteLeave(to, from, next) {
      let position = window.scrollY; //记录离开页面的位置
      if (position == null) position = 0;
      this.$store.commit("changeRecruitScrollY", position); //离开路由时把位置存起来
      next();
    },
    watch: {
      $route(to, from) {
        if (to.name === "lyzdInterfaceList") {
          //跳转的的页面的名称是"NewRecruit",这里就相当于我们listview页面，或者原始页面
          let recruitScrollY = this.$store.state.recruitScrollY;
          window.scroll(0, recruitScrollY);
        }
      },
    },

    handleInfo: function(index, row) {
      let api_id = row.id;
      this.$router.push({ path: "/interface_info/cid=" + api_id });
    },
    handleInfoCopy: function(index, row) {
      let api_id = row.id;
      this.$router.push({ path: "/interface_info_copy/cid=" + api_id });
    },
    //显示新增界面
    handleAdd: function() {
      this.addFormVisible = true;
    },
    //编辑
    editSubmit: function() {
      let self = this;
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            self.editLoading = true;
            //NProgress.start();
            let params = {
              id: self.editForm.id,
              env_name: self.editForm.env_name,
              address: self.editForm.address,
              content: self.editForm.content,
            };
            //alert(params)
            let header = {
              "Content-Type": "application/json",
              Authorization:
                "Token " + JSON.parse(sessionStorage.getItem("token")),
            };
            updateEnvironment(header, params).then((_data) => {
              let { msg, code, data } = _data;
              self.editLoading = false;
              if (code === "999999") {
                self.$message({
                  message: "修改成功",
                  center: true,
                  type: "success",
                });
                self.$refs["editForm"].resetFields();
                self.editFormVisible = false;
                self.getLyzdEnterfaceList();
              } else if (code === "999997") {
                self.$message.error({
                  message: msg,
                  center: true,
                });
              } else {
                self.$message.error({
                  message: msg,
                  center: true,
                });
              }
            });
          });
        }
      });
    },
    //新增
    addSubmit: function() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          let self = this;
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            self.addLoading = true;
            //NProgress.start();
            let params = JSON.stringify({
              env_name: self.addForm.env_name,
              address: self.addForm.address,
              content: self.addForm.content,
            });
            let header = {
              "Content-Type": "application/json",
              Authorization:
                "Token " + JSON.parse(sessionStorage.getItem("token")),
            };
            addEnvironment(header, params).then((_data) => {
              let { msg, code, data } = _data;
              self.addLoading = false;
              if (code === "999999") {
                self.$message({
                  message: "添加成功",
                  center: true,
                  type: "success",
                });
                self.$refs["addForm"].resetFields();
                self.addFormVisible = false;
                self.getLyzdEnterfaceList();
              } else if (code === "999997") {
                self.$message.error({
                  message: msg,
                  center: true,
                });
              } else {
                self.$message.error({
                  message: msg,
                  center: true,
                });
                self.$refs["addForm"].resetFields();
                self.addFormVisible = false;
                self.getLyzdInterfaceList();
              }
            });
          });
        }
      });
    },
    selsChange: function(sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function() {
      let ids = this.sels.map((item) => item.id);
      let self = this;
      this.$confirm("确认删除选中记录吗？", "提示", {
        type: "warning",
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        let self = this;
        let params = { ids: ids };
        let header = {
          "Content-Type": "application/json",
          Authorization: "Token " + JSON.parse(sessionStorage.getItem("token")),
        };
        delEnvironment(header, params).then((_data) => {
          let { msg, code, data } = _data;
          if (code === "999999") {
            self.$message({
              message: "删除成功",
              center: true,
              type: "success",
            });
          } else {
            self.$message.error({
              message: msg,
              center: true,
            });
          }
          self.getLyzdInterfaceList();
        });
      });
    },
  },
  mounted() {
    this.getLyzdInterfaceList();
  },
};
</script>

<style lang="scss" scoped></style>
